
//将div转为图片
/**
 *
 * @param domId dom元素id
 * @param fun   回调方法
 * @param isDownload  是否下载
 */
export function divToImg(domId,fun,isDownload) {
  var getPixelRatio = function (context) { // 获取设备的PixelRatio
    var backingStore = context.backingStorePixelRatio ||
      context.webkitBackingStorePixelRatio ||
      context.mozBackingStorePixelRatio ||
      context.msBackingStorePixelRatio ||
      context.oBackingStorePixelRatio ||
      context.backingStorePixelRatio || 0.5;
    return (window.devicePixelRatio || 0.5) / backingStore;
  };

  //生成的图片名称
  var imgName = "cs.jpg";
  var shareContent = document.getElementById(domId);
  var width = shareContent.offsetWidth;
  var height = shareContent.offsetHeight;
  var canvas = document.createElement("canvas");
  var context = canvas.getContext('2d');
  var scale = getPixelRatio(context); //将canvas的容器扩大PixelRatio倍，再将画布缩放，将图像放大PixelRatio倍。
  canvas.width = width * scale;
  canvas.height = height * scale;
  canvas.style.width = width + 'px';
  canvas.style.height = height + 'px';
  context.scale(scale, scale);

  var opts = {
    scale: scale,
    canvas: canvas,
    width: width,
    height: height,
    dpi: window.devicePixelRatio,
    useCORS: true,
    backgroundColor:null
  };
  var dataUrl=null;
  html2canvas(shareContent, opts).then(function (canvas) {
    context.imageSmoothingEnabled = false;
    context.webkitImageSmoothingEnabled = false;
    context.msImageSmoothingEnabled = false;
    context.imageSmoothingEnabled = false;
    dataUrl= canvas.toDataURL('image/jpeg', 1.0);
    fun(dataUrl);

    if(isDownload){
      var a = document.createElement('a')
      //指定下载文件名称
      a.href = dataUrl;
      a.download = "img"
      //a 标签 需要点击触发。所以强制给他分派一个点击事件
      //创建一个鼠标事件
      let event = document.createEvent("MouseEvents")
      // 初始化鼠标事件
      event.initMouseEvent("click", true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null)
      // 指定元素对象触发事件
      a.dispatchEvent(event)
    }

  });
}

//保留N位小数并返回number类型
export function toFixed(num,precision) {
  return parseFloat((num).toFixed(precision));
}

